package com.baohua.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;

import com.baohua.dao.OrderDao;
import com.baohua.model.Dictionary;
import com.baohua.model.DiningTable;
import com.baohua.model.Goods;
import com.baohua.model.OrdDinTabRel;
import com.baohua.model.OrderDetails;
import com.baohua.model.OrderHeader;
import com.baohua.util.StringUtil;

@Component("orderDao")
public class OrderDaoImpl implements OrderDao {

	private SessionFactory sessionFactory;
	
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	@Resource(name="sessionFactory")
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	/**
	 * 该方法当属字典类，取代方法：DictionaryDaoImpl.findDictionaryByCode
	 */
	@Deprecated 
	@SuppressWarnings("unchecked")
	@Override
	public List<Dictionary> findCategoryByCode(String categoryCode) {
		
		String hql = "from Dictionary d where d.dictionaryPId = " +
				"(select i.dictionaryId from Dictionary i where i.categoryCode = ?)";
		Query q = sessionFactory.getCurrentSession().createQuery(hql);
		q.setString(0, categoryCode);
		
		return (List<Dictionary>)q.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Goods> findDishByGoodsCategory(long categoryId) {
		String hql = "from Goods g where g.goodsCategory = ?";
		Query q = sessionFactory.getCurrentSession().createQuery(hql).setLong(0, categoryId);
		return (List<Goods>)q.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<DiningTable> findDiningTableByCategoryId(long categoryId) {
		String hql = "from DiningTable d where d.diningTableCategory = ?";
		Query q = sessionFactory.getCurrentSession().createQuery(hql).setLong(0, categoryId);
		return (List<DiningTable>)q.list();
	}

	@Override
	public long saveOrderHeader(OrderHeader orderHeader) {
		sessionFactory.getCurrentSession().save(orderHeader);
		return orderHeader.getOrderHeaderId();
	}

	@Override
	public void saveListOrderDining(List<OrdDinTabRel> orderDining) {
		
		Session session = sessionFactory.getCurrentSession();
		
		for(int i = 0; i < orderDining.size(); i++) {
			OrdDinTabRel odtr = orderDining.get(i);
			session.save(odtr);
			if(i % StringUtil.BATCH_SIZE == 0) {
				session.flush();
				session.clear();
			}
		}
	}

	@Override
	public void saveListOrderDetails(List<OrderDetails> listOrderDetails) {
		Session session = sessionFactory.getCurrentSession();
		
		for(int i = 0; i < listOrderDetails.size(); i++) {
			OrderDetails ods = listOrderDetails.get(i);
			session.save(ods);
			if(i % StringUtil.BATCH_SIZE == 0) {
				session.flush();
				session.clear();
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<OrderHeader> findListOrderHeader(String whereSql, int startPost, int pageSize) {
		
		String hql = "from OrderHeader o where 1=1 " + whereSql 
				+ " order by o.orderDate desc, o.orderStatus asc, o.orderCategory asc";
		
		Query q = sessionFactory.getCurrentSession().createQuery(hql);
			q.setFirstResult(startPost).setMaxResults(pageSize);
			
		return (List<OrderHeader>)q.list();
	}

	@Override
	public long queryCountOrderHeader(String whereSql) {
		long result = 0;
		String hql = "select count(*) from OrderHeader o where 1=1 " + whereSql;
		Object obj = sessionFactory.getCurrentSession().createQuery(hql).uniqueResult();
		if(obj == null)
			return result;
		result = Long.parseLong(obj.toString());
		return result;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<OrderDetails> findOrderDetailsByOrderHeaderId(long orderHeaderId) {
		return (List<OrderDetails>)sessionFactory.getCurrentSession()
				.createQuery("from OrderDetails o where o.orderHeader.orderHeaderId = ?")
				.setLong(0, orderHeaderId).list();
	}

	@Override
	public int updateOrderByOrderHeaderId(long orderHeaderId, long dictionaryId) {
		int result = -1;
		String hql = "update OrderHeader o set o.orderStatus = ? where o.orderHeaderId = ?";
		result = sessionFactory.getCurrentSession().createQuery(hql)
		.setLong(0, dictionaryId).setLong(1, orderHeaderId).executeUpdate();
		return result;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Goods> findAllGoods() {
		return (List<Goods>)sessionFactory.getCurrentSession().createQuery("from Goods g order by g.goodsCategory desc").list();
	}

	@Override
	public int updateOrderDetails(JSONArray modifyGoods) {
		int result = 0;
		Session session = sessionFactory.getCurrentSession();
		String hql = "update OrderDetails o set o.amount = ?, o.goodsTotalSalesPrice = ? where o.orderDetailsId = ?";
		for(int i = 0; i < modifyGoods.size(); i++) {
			JSONObject jo = modifyGoods.getJSONObject(i);
			long orderDetailsId = jo.getLong("orderDetailsId");
			int amount = jo.getInt("amount");
			double goodsTotalSalesPrice = jo.getDouble("goodsTotalSalesPrice");
			
			Query q = session.createQuery(hql).setInteger(0, amount).setDouble(1, goodsTotalSalesPrice).setLong(2, orderDetailsId);
			result = q.executeUpdate();
			if(i % StringUtil.BATCH_SIZE == 0) {
				session.flush();
				session.clear();
			}
		}
		return result;
	}

	@Override
	public void deleteOrderDetails(List<OrderDetails> lists) {
		Session session = sessionFactory.getCurrentSession();
		for(int i = 0; i < lists.size(); i++) {
			OrderDetails ods = lists.get(i);
			session.delete(ods);
		}
	}

	@Override
	public double findGoodsTotalPriceByOrderHeaderId(long orderHeaderId) {
		Session session = sessionFactory.getCurrentSession();
		session.flush();
		session.clear();
		Object obj = session.createQuery("select sum(o.goodsTotalSalesPrice) from OrderDetails o where o.orderHeader.orderHeaderId = ?")
		.setLong(0, orderHeaderId).uniqueResult();
		double totalPrice = Double.parseDouble(obj.toString());
		return totalPrice;
	}

	@Override
	public int findGoodsCountByOrderHeaderId(long orderHeaderId) {
		Session session = sessionFactory.getCurrentSession();
		session.flush();
		session.clear();
		Object obj = session.createQuery("select sum(o.amount) from OrderDetails o where o.orderHeader.orderHeaderId = ?")
				.setLong(0, orderHeaderId).uniqueResult();
		int amount = Integer.parseInt(obj.toString());
		return amount;
	}

	@Override
	public void updateOrderHeader(String hql) {
		sessionFactory.getCurrentSession().createQuery(hql).executeUpdate();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<DiningTable> queryAllDiningTable() {
		return (List<DiningTable>)sessionFactory.getCurrentSession().createQuery("from DiningTable d order by d.diningTableName").list();
	}

	@Override
	public void deleteOrdTabRelByOrderHeaderId(long orderHeaderId) {
		sessionFactory.getCurrentSession().createQuery("delete from OrdDinTabRel o where o.orderHeader.orderHeaderId = ?").setLong(0, orderHeaderId).executeUpdate();
	}

	@Override
	public int deleteTableByJA(JSONArray ja, long orderHeaderId) {
		int result = 0;
		Session session = sessionFactory.getCurrentSession();
		String hql = "delete from OrdDinTabRel o where o.orderHeader.orderHeaderId = ? and o.diningTable.diningTableId = ?";
		for(int i = 0; i < ja.size(); i++) {
			JSONObject jo = ja.getJSONObject(i);
			long diningTableId = jo.getLong("diningTableId");
System.out.println(diningTableId);
			Query q = session.createQuery(hql)
					.setLong(0, orderHeaderId).setLong(1, diningTableId);
			result = q.executeUpdate();
			if(i % StringUtil.BATCH_SIZE == 0) {
				session.flush();
				session.clear();
			}
		}
		return result;
	}

	@Override
	public void addTables(List<OrdDinTabRel> odtrLists) {
		Session session = sessionFactory.getCurrentSession();
		for(int i = 0; i < odtrLists.size(); i++) {
			OrdDinTabRel odtr = odtrLists.get(i);
			session.save(odtr);
			if(i % StringUtil.BATCH_SIZE == 0) {
				session.flush();
				session.clear();
			}
		}
		
	}
}
